/***
 * @Author:xxx
 * @Date:2020-08-21 18:11:24
 * @LastModifiedBy:xxx
 * @Last Modified time:2020-08-21 18:11:24
 */

import React, { Component } from 'react';
import './home.css';
import ReactEcharts from 'echarts-for-react';
import echarts from 'echarts';
import { getOption1, getOption2, getOption3, getChinaMap } from '../../components/echarts/home-echarts';
import { message } from 'antd';
import { connect } from 'react-redux';
import { reqGetDefaultMb, getHomeInfo, getChinaMapInfo, refreshHomeInfo } from '../../api';
import { setDefaultMb } from '../../utils/storageUtils';
import { setDefaultMbInReducer, logout, setChinaMap } from '../../redux/actions';
import geoJson from '../../assets/china.json'
import { FullScreenContainer, ScrollBoard } from '@jiaminghi/data-view-react'
import icon1 from '../../assets/image/icon1.png'
import icon2 from '../../assets/image/icon2.png'
import icon3 from '../../assets/image/icon3.png'
import icon4 from '../../assets/image/icon4.png'
import icon5 from '../../assets/image/icon5.png'
import icon7 from '../../assets/image/icon7.png'
import backMenuBg from '../../assets/image/back-menu.png'
import { RedoOutlined } from '@ant-design/icons';


const homeNameBox = [{
  index: 0,
  name: '已接入矿区数量',
}, {
  index: 1,
  name: '已接入用户数量',
}, {
  index: 2,
  name: '已接入部门数量',
}, {
  index: 3,
  name: '测井数据数量',
}, {
  index: 4,
  name: '本月数据上传量',
}]
let setInterTime = null
class Home extends Component {

  constructor(props) {
    super(props);
    this.state = {
      barData: [],
      tableData: {},
      homeSmallBox: [],
      yData: [],
      seriesData: [],
      weather: '',
      todayDate: '',
      currentTime: '',
      clientHeight: 0,
    }
  }
  // setOrgInfo = () => {
  //   const org_id = this.props.user.org.org_id;
  //   const org_pid = this.props.user.org.org_pid;
  //   console.log("组织信息",this.props.user)
  //   this.props.orgInfo(org_id,org_pid);  // 发 获取组织信息 的异步请求，有了结果后更新状态  
  // }

  getDefaultMb = async () => {   // 获取默认模板
    const user_mobile = this.props.user.user_mobile;
    const result = await reqGetDefaultMb(user_mobile);
    // console.log("获取默认模板",result);
    if (result.code === 200) {
      const defaultMb = result.data;
      if (defaultMb.mb_id) {
        this.props.setDefaultMbInReducer(defaultMb);   // 存入 默认模板reducer
        setDefaultMb(defaultMb);   // 将模板存入 内存
      }
    }
  }

  getHomeData = async () => {

    //点击地图进来的就可以获取到 矿区id否则获取不到
    let coal_id = window.location.hash.split("?")[1];
    // console.log("coal_id",coal_id)
    let result
    if (coal_id) {

      window.localStorage.setItem("organizationId", coal_id)
      result = await getHomeInfo(coal_id);
      console.log("获取矿区首页数据", result);

    } else if (window.localStorage.getItem("org_id") && window.localStorage.getItem("organizationId") == null) {
      // console.log(33)
      result = await getHomeInfo(window.localStorage.getItem("org_id"));
      console.log("获取全部首页数据", result);
    } else if (window.localStorage.getItem("org_id")) {
      result = await getHomeInfo(window.localStorage.getItem("organizationId"));
      console.log("获取矿区首页数据", result);
    } else {
      message.error("登录失败")
    }

    let data = result.data;
    this.setState({
      homeSmallBox: [data.organizationSum, data.userSum, data.workspaceSum, data.drillSum, data.monthUploadSum]
    })

    //初始化柱状图数据
    this.setState({
      barData: result.data.annualDrillDistribution
    })


    let yData_arr = [], seriesData_arr = [];

    data.workFaceInfo && data.workFaceInfo.map(item => {
      yData_arr.push(item.workFaceName)
      seriesData_arr.push(item.workFaceSum)
    })

    // 获取工作面钻孔统计图
    this.setState({
      yData: yData_arr,
      seriesData: seriesData_arr
    })
    let rowNum = 0
    if (data.latestDrillInfo.length > 10) {
      rowNum = 10
    } else {
      rowNum = data.latestDrillInfo.length - 1
    }
    const newData = {
      header: ['矿区', '文件名', '上传时间', '操作人'],
      data: [],
      rowNum: rowNum,
      headerHeight: 46,
      headerBGC: 'rgba(16, 49, 98, 0.8)',
      evenRowBGC: 'rgba(25, 142, 232, 0)',
      oddRowBGC: 'rgba(25, 142, 232, 0)',
    }
    data.latestDrillInfo.forEach(item => {
      newData.data.push([
        item.drillName, item.drillDocumentName, item.createTime, item.operator
      ])
    })
    this.setState({
      tableData: newData,
      clientHeight: (rowNum * 50) + 46
    })
    // const result = await getHomeInfo(id); 


    // if(result.code === 200){
    //   const defaultMb = result.data;
    //   if(defaultMb.mb_id){
    //     this.props.setDefaultMbInReducer(defaultMb);   // 存入 默认模板reducer
    //     setDefaultMb(defaultMb);   // 将模板存入 内存
    //   }
    // }  
  }
  getChinaMapData = async () => {
    const result = await getChinaMapInfo();
    const data = []
    geoJson.features.forEach(item => {
      result.data.forEach(items => {
        if (item.properties.name.slice(0, 2) === items.name.slice(0, 2)) {
          data.push({
            detail: items.detail,
            name: item.properties.name
          })
        }
      })
    });
    const myChart = await echarts.init(document.getElementById('mainMap'));
    const options = getChinaMap(data)
    await echarts.registerMap('china', geoJson)
    await myChart.setOption(options);
  }
  getTime() {
    this.setState({
      todayDate: new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
    })
    // 先调用一次
    this.getCurrentTime()
    // 开启定时器
    setInterTime = setInterval(() => this.getCurrentTime(), 1000)
  }
  // 获取当前时间
  getCurrentTime() {
    const date = new Date()
    const hour = (10 > date.getHours()) ? '0' + date.getHours() : date.getHours()
    const minute = (10 > date.getMinutes()) ? '0' + date.getMinutes() : date.getMinutes()
    this.setState({
      currentTime: hour + ':' + minute
    })
  }
  getWeather() {
    fetch('http://wthrcdn.etouch.cn/weather_mini?city=西安')
      .then(res => res.json())
      .then(data => {
        const list = data.data.forecast
        const wList = [];
        for (let i = 0; i < 3; i++) {
          const item = list[i];
          const high = item.high.split(" ")[1];
          const low = item.low.split(" ")[1];
          wList.push({
            day: item.date.slice(-3),
            type: item.type,
            temperature: high + "/" + low
          });
        }
        this.setState({
          weather: wList[0]
        })
        console.log(data)
      })
  }
  componentWillMount() {
    this.getTime()
    this.getWeather()
    this.getDefaultMb();

    // 获取首页数据
    this.getHomeData();
    this.getChinaMapData();
  }
  componentDidMount() {

    // 4个echarts的页面自适应
    let myChart1 = this.echarts1 && this.echarts1.getEchartsInstance();
    let myChart2 = this.echarts2 && this.echarts2.getEchartsInstance();
    let myChart3 = this.echarts3 && this.echarts3.getEchartsInstance();
    // let myChart4 = this.echarts4&&this.echarts4.getEchartsInstance();

    window.addEventListener('resize', () => {
      myChart1 && myChart1.resize();
      myChart2 && myChart2.resize();
      myChart3 && myChart3.resize();
      //myChart4&&myChart4.resize(); 
    })
  }
  componentWillUnmount() {
    // 清除定时器
    clearInterval(setInterTime)
  }
  // 返回主菜单
  backMenu() {
    this.props.history.push('/orgzanition-mgt')
  }
  handleLogout = () => {
    this.props.logout();
    this.props.setChinaMap({ chinaMap: '/' })
    this.props.history.replace('/#/login');
    localStorage.removeItem('chinaMap');
  };
  refreshData = async () => {
    const key = 'refreshData'
    message.loading({
      content: '刷新中...',
      key,
      duration: 0
    });
    const result = await refreshHomeInfo()
    if (result.code === 200) {
      message.success({
        content: '手动刷新成功',
        key,
        duration: 2,
      });
    }
  }
  render() {
    const { tableData, clientHeight } = this.state
    return (
      <FullScreenContainer>
        <div className="home-wrapper">
          <div className="home-top" style={{ height: '5.25em' }}>
            <div className='home-title'>矿井钻孔分析仪数据处理软件</div>
            <div className='home-top-content'>
              <div className='home-top-left'>
                <img src={backMenuBg} alt="" onClick={() => { this.backMenu() }} />
              </div>
              <div className='home-top-right'>
                <img src={icon5} alt="" style={{ width: '1.5rem' }} />
                <div style={{ marginLeft: '0.625rem', fontSize: '1.625rem', lineHeight: '1.625rem' }}>
                  {this.state.weather.temperature}
                </div>
                <div style={{ marginLeft: '1.875rem', fontSize: '1.625rem', lineHeight: '1.625rem' }}>{this.state.currentTime}</div>
                <div style={{ height: '2em', width: 1, background: '#ffffff', margin: '0 1rem' }}>
                </div>
                <div style={{ fontSize: '0.75rem', lineHeight: '0.75rem' }}>
                  <div>
                    {this.state.weather.day}
                  </div>
                  <div style={{ marginTop: '0.6875em' }}>
                    {this.state.todayDate}
                  </div>
                </div>
                <div className='user-setting' style={{ marginLeft: '1.25rem' }} onClick={this.refreshData}>
                  <RedoOutlined style={{ color: '#64eaff', fontSize: '1.25rem' }} />
                  <div style={{ fontSize: '1rem', marginLeft: '0.625rem', lineHeight: '0.625rem' }}>刷新</div>
                </div>
                <div className='user-exit' onClick={this.handleLogout} style={{ marginLeft: '1.25rem' }}>
                  <img src={icon7} alt="" style={{ width: '1.25rem' }} />
                  <div style={{ fontSize: '1rem', marginLeft: '0.625rem', lineHeight: '0.625rem' }}>退出</div>
                </div>
              </div>
            </div>
          </div>
          <div className="home-content">
            <div className="content-item3">
              <div className="big-box" style={{ width: '25rem', height: '19em' }}>
                <div className="big-box-top">
                  <img src={icon1} alt="" style={{ marginRight: '0.6875rem', width: "1.5rem" }} />
                  <div>年度测井分布</div>
                </div>
                {/* 这部分的标题最好是Echarts里的，下面的类似 */}
                <div className="echarts-box" style={{ height: '100%', marginTop: "0.625em", overflow: 'hidden' }}>
                  <ReactEcharts
                    ref={(e) => { this.echarts1 = e; }}
                    option={getOption1(this.state.barData)}
                    style={{ width: '100%', height: '100%' }}
                  // theme={'dark'}
                  />
                </div>
              </div>
              <div className="big-box" style={{ width: '25rem', height: '19em', marginTop: '0.625em' }}>
                <div className="big-box-top">
                  <img src={icon2} alt="" style={{ marginRight: '0.6875rem', width: '1.5rem' }} />
                  <div>工作面钻孔统计图</div>
                </div>
                <div className="echarts-box" style={{ height: '100%', marginTop: "0.625em" }}>
                  <ReactEcharts
                    ref={(e) => { this.echarts3 = e; }}
                    option={getOption3(this.state.yData, this.state.seriesData)}
                    style={{ width: '100%', height: '100%' }}
                  />
                </div>
              </div>
              <div className="big-box" style={{ width: '25rem', height: '20.1875em', marginTop: '0.625em' }}>
                <div className="big-box-top">
                  <img src={icon3} alt="" style={{ marginRight: '0.6875rem', width: '1.5rem' }} />
                  <div>测井仪器使用占比图</div>
                </div>
                <div className="echarts-box" style={{ height: '100%', marginTop: "0.625em" }}>
                  <ReactEcharts
                    ref={(e) => { this.echarts2 = e; }}
                    option={getOption2()}
                    style={{ width: '100%', height: '100%' }}
                  />
                </div>
              </div>
            </div>

            <div className='content-item2' style={{ minHeight: 320, position: 'relative' }}>
              <div className='content-item2-info'>
                {
                  this.state.homeSmallBox.map((item, index) => {
                    return (
                      <div className='info'>
                        <h3>{item}</h3>
                        <span>{homeNameBox[index].name}</span>
                      </div>
                    )
                  })
                }

              </div>
              <div id='mainMap' style={{ height: '100%', width: '100%' }}></div>
              {/* <div className='backMenu' onClick={() => { this.backMenu() }}>返回主菜单</div> */}
            </div>

            <div className="content-item3">
              <div className="big-box">
                <div className="big-box-top">
                  <img src={icon4} alt="" style={{ marginRight: '0.6875rem', width: '1.5rem' }} />
                  <div>最新测井数据列表</div>
                </div>
                {/* <div className="box-title">最新测井数据列表</div> */}
                <div className="echarts-box" style={{ height: '100%', marginTop: "0.625em" }}>
                  <ScrollBoard config={tableData} style={{ width: '100%', height: clientHeight }} />

                  {/* <Table columns={columns} dataSource={this.state.tableData} size="small" scroll={{ y: 'calc(100vh - 75vh)' }} pagination={false} /> */}
                  {/* <ReactEcharts
                   ref={(e) => { this.echarts4 = e;}}
                   option={getOption4()}
                   style={{width: '100%', height: '100%'}}
                 /> */}
                </div>
              </div>

            </div>
          </div>
        </div>
      </FullScreenContainer >
    )
  }
}

export default connect(
  state => ({ user: state.user, defaultmbData: state.defaultmbData }),
  { setDefaultMbInReducer, logout, setChinaMap }
)(Home);